package main.java.com.fmanager.services.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import main.java.com.fmanager.dao.UserDAO;
import main.java.com.fmanager.dao.UserRoleDAO;
import main.java.com.fmanager.models.User;
import main.java.com.fmanager.models.UserAdditionDetial;
import main.java.com.fmanager.models.UserRole;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

	@Resource
	private UserDAO userDAO;
	
	@Resource
	private UserRoleDAO userRoleDAO;
	
	@Override
	public UserDetails loadUserByUsername(String uName) throws UsernameNotFoundException {
		
		User user = userDAO.findByEmail(uName);

        if(user == null) {
            throw new UsernameNotFoundException(String.format("The username %s doesn't exist", uName)); //$NON-NLS-1$
        }

        
        List<UserRole> roles =userRoleDAO.getUserRoleByUserId(user.getId());
        
        List<GrantedAuthority> authorities = new ArrayList<>();
        
        roles.forEach(role -> {
            authorities.add(new SimpleGrantedAuthority(role.getRoleName()));
        });
        
        UserDetails userDetails = new UserAdditionDetial(user.getId(), user.getUserName(), user.getPassword(), authorities);

        return userDetails;
	}

}
